package br.ufpb.di.knowledgetv.sqtv.services;

import java.util.ArrayList;
import java.util.List;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import org.springframework.stereotype.Component;

import br.ufpb.di.knowledgetv.sqtv.utils.SPARQLUtils;

import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;

//@Component
public class BBCProgrammeService extends AbstractService {


	@Override
	public List<Resource> searchByKeyword(String keyword) {
		List<Resource> result = new ArrayList<Resource>();

        try {
            String sparql = SPARQLUtils.readFileSparql(getClass().getResource("/sparqls/query_bbc.sparql").getPath(), keyword);
            ResultSet rs = SPARQLUtils.executeQuery("http://lod.openlinksw.com/sparql", sparql);
            if(rs == null) {
                return result;
            }

            while (rs.hasNext()) {
                QuerySolution qs = rs.next();
                Resource resource = qs.getResource("thing");

                resource.addLiteral(RDFS.label, qs.getLiteral("title"));
                resource.addLiteral(RDFS.comment, qs.getLiteral("synopsis"));
                resource.addProperty(RDF.type, qs.getResource("type"));
                resource.addProperty(RDFS.domain, this.beanName);
                Resource inResult;
                if((inResult = verifyExistance(resource, result)) != null) {
                    inResult.getModel().union(resource.getModel());
                } else {
                    result.add(resource);
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            return result;
        }
	}

    @Override
    public Model getModel(String url) {
        Model model = ModelFactory.createDefaultModel();
        return model.read(url);
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }
}
